package com.wjw.leetcode;

import com.wjw.common.ListNode;

import java.util.HashSet;
import java.util.Set;

/**
 * linked-list-cycle
 * 环形链表
 */
public class leetcode141 {

    // 哈希表
    public boolean hasCycle1(ListNode head) {
        Set<ListNode> set = new HashSet<ListNode>();
        while (head != null) {
            if (set.contains(head)) {
                return true;
            }
            set.add(head);
            head = head.next;
        }
        return false;
    }

    // 快慢指针
    public boolean hasCycle2(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (slow != null && fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }
}
